package com.game.redis;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

/**
 * @author SunChong
 */
public abstract class MemKey {
	public final static int NULL = 0;
	public final static int SENCOND = 1;
	public final static int MINUTE = SENCOND * 60;
	public final static int HOUR = MINUTE * 60;
	public final static int DAY = HOUR * 24;
	public final static int MONTH = DAY * 30;

	//falg是当前大类下的唯一标识
	private String subFlag;
	//多少秒后过期
	private int expiredTime;

	public MemKey(String subFlag, int expiredTime) {
		this.subFlag = subFlag;
		this.expiredTime = expiredTime;
	}

	public MemKey() {
		this("");
	}

	/**
	 * 默认为到今晚0点过期
	 *
	 * @param subFlag
	 */
	public MemKey(String subFlag) {
		this.subFlag = subFlag;
		String s = DateTime.now().plusDays(1).toString("yyyy-MM-dd");
		DateTime parse = DateTime.parse(s, DateTimeFormat.forPattern("yyyy-MM-dd"));
		long l = (parse.getMillis() - DateTime.now().getMillis()) / 1000;
		this.expiredTime = (int) l;
	}

	/**
	 * @param subFlag
	 * @param timeStr 过期时间,格式=“yyyy-MM-dd HH:mm:ss”
	 */
	public MemKey(String subFlag, String timeStr) {
		this.subFlag = subFlag;
		DateTime parse = DateTime.parse(timeStr, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
		DateTime now = DateTime.now();
		if (now.getMillis() > parse.getMillis()) {
			try {
				throw new Exception("超时时间比现在还早，还存个屁");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		this.expiredTime = (int) ((now.getMillis() - parse.getMillis()) / 1000);
	}

	public abstract String getModularFlag();

	@Override
	public String toString() {
		return getModularFlag() + "_" + subFlag;
	}

	public MemInfo build(Object obj) {
		return new MemInfo(toString() + "_" + obj, expiredTime);
	}

	public static void main(String[] args) {
		MemKey memKey = new MemKey("bbb") {
			@Override
			public String getModularFlag() {
				return "aaa";
			}
		};
		MemInfo ccc = memKey.build("ccc");
		System.out.println();
	}
}
